package com.yupi.springbootinit.messagecenter;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yupi.springbootinit.mapper.DepartmentMapper;
import com.yupi.springbootinit.mapper.WorkflowTaskMapper;
import com.yupi.springbootinit.model.entity.Department;
import com.yupi.springbootinit.model.entity.WorkflowTask;
import com.yupi.springbootinit.mq.EventEnvelope;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * 最终检验事件消费者：quality.final.inspection.ready
 * 幂等依据：bizType=PROCESS_SHEET + bizId=processSheetId + taskType=QUALITY_FINAL_INSPECTION
 */
@Slf4j
@Component
public class QualityFinalInspectionListener {

    private static final String TASK_TYPE_QUALITY_FINAL = "QUALITY_FINAL_INSPECTION";
    private static final String BIZ_TYPE_PROCESS_SHEET = "PROCESS_SHEET";

    private static final String STATUS_PENDING = "PENDING";
    private static final String PRIORITY_NORMAL = "NORMAL";

    // 品质部部门编码（按拼音首字母大写+001）
    private static final String QA_DEPT_CODE = "PZ001";

    @Resource
    private WorkflowTaskMapper workflowTaskMapper;

    @Resource
    private DepartmentMapper departmentMapper;

    // @RabbitListener(queues = RabbitMqConfig.QUEUE_QUALITY_FINAL_READY)  // RabbitMQ 已暂停使用
    public void onFinalReady(EventEnvelope env) {
        try {
            Object p = (env == null ? null : env.payload());
            if (!(p instanceof java.util.Map<?, ?>)) {
                log.warn("final inspection payload empty or not a map");
                return;
            }
            java.util.Map<?, ?> raw = (java.util.Map<?, ?>) p;
            Long processSheetId = toLong(raw.get("processSheetId"));
            String orderNumber = toStr(raw.get("orderNumber"));
            String productName = toStr(raw.get("productName"));
            if (processSheetId == null) {
                log.warn("final inspection missing processSheetId");
                return;
            }

            // 幂等：已存在则跳过
            Long exists = workflowTaskMapper.selectCount(new QueryWrapper<WorkflowTask>()
                    .eq("bizType", BIZ_TYPE_PROCESS_SHEET)
                    .eq("bizId", processSheetId)
                    .eq("taskType", TASK_TYPE_QUALITY_FINAL)
                    .eq("isDelete", 0)
            );
            if (exists != null && exists > 0) {
                log.info("final inspection task already exists, processSheetId={}", processSheetId);
                return;
            }

            Department qaDept = getDeptByCode(QA_DEPT_CODE);
            if (qaDept == null) {
                log.error("final inspection create failed: dept {} not found", QA_DEPT_CODE);
                return;
            }

            // 创建品质最终检验任务
            WorkflowTask task = new WorkflowTask();
            task.setTaskTitle("最终检验");
            task.setTaskDescription("订单最终检验 - " + Objects.toString(productName, ""));
            task.setTaskType(TASK_TYPE_QUALITY_FINAL);
            task.setBizType(BIZ_TYPE_PROCESS_SHEET);
            task.setBizId(processSheetId);
            task.setBizNumber(orderNumber);
            task.setProductName(productName);
            task.setDepartmentId(qaDept.getId());
            task.setDepartmentName(qaDept.getDepartmentName());
            task.setTaskStatus(STATUS_PENDING);
            task.setPriority(PRIORITY_NORMAL);
            LocalDateTime now = LocalDateTime.now();
            task.setCreateTime(now);
            task.setUpdateTime(now);
            task.setIsDelete(0);

            int rows = workflowTaskMapper.insert(task);
            log.info("created final inspection task: processSheetId={}, order={}, rows={}",
                    processSheetId, orderNumber, rows);

        } catch (Exception e) {
            log.warn("consume final inspection failed", e);
            // 让消息进入DLQ，由DLQ监听器记录
            throw e;
        }
    }

    private Department getDeptByCode(String code) {
        if (StringUtils.isBlank(code)) return null;
        return departmentMapper.selectOne(
                new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<Department>()
                        .eq(Department::getDepartmentCode, code)
                        .eq(Department::getIsDelete, 0)
                        .last("limit 1")
        );
    }

    private static Long toLong(Object v) {
        if (v == null) return null;
        if (v instanceof Number n) return n.longValue();
        try { return Long.parseLong(v.toString()); } catch (Exception e) { return null; }
    }

    private static String toStr(Object v) {
        return v == null ? null : v.toString();
    }
}